package middleware

import (
	"bawei_shop/api/internal/types"
	"bawei_shop/api/pkg"
	"context"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

type AuthTokenMiddleware struct {
}

func NewAuthTokenMiddleware() *AuthTokenMiddleware {
	return &AuthTokenMiddleware{}
}

func (m *AuthTokenMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		token := r.Header.Get("token")
		if token == "" {
			resp := &types.Response{
				Code: 10001,
				Msg:  "token获取失败",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		//contest 上下文创术数据 userID
		payload := pkg.CheckJwt("wangyashuo", token)
		if payload == "" {
			res := types.Response{
				Code: -2,
				Msg:  "token效验失败",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, res)
			return
		}
		value := context.WithValue(r.Context(), "userId", payload)
		next(w, r.WithContext(value))
	}
}
